from common import BaseRequestHandler
from lib.dbobjects import Profiler
from lib.common_cards import CardDeck, Player, get_top_combo

from datetime import datetime

from google.appengine.api.users import User
from google.appengine.api import users

_RESULT_MESSAGES = {0:"Your hand does not have any combination. ",
                    1:"Your hand has a pair, " + \
                            "but unfortunately it is below the Jack. ",
                    2:"Congrats. You got a pair of Jacks or Higher. ",
                    3:"Nice. You got two pairs. ",
                    4:"Awesome. Three of a kind. ",
                    5:"Nicely done! A straight. ",
                    6:"What do we have here? A flush! ",
                    7:"Hmm ... 3 + 2, isn't this a full house?! ",
                    8:"Unbelievable! You've got a FOUR-OF-A-KIND! ",
                    9:"Congratulations!!! This is a STRAIGHT-FLUSH!!! ",
                    10:"AS GOOD AS IT GETS!!! ROYAL-STRAIGHT-FLUSH!!!"}

_RESULTS_TABLE = {0:"No combination",
                  1:"Pair below the Jack",
                  2:"Pair of Jacks or Higher",
                  3:"Two pairs",
                  4:"Three of a kind",
                  5:"Straight",
                  6:"Flush",
                  7:"Full house (3 + 2)",
                  8:"Four of a kind",
                  9:"Straight Flush",
                  10:"Royal Straight Flush"}

_COMBO_PAYOFFS = {0:-1,
                  1:-1,
                  2:1,
                  3:2,
                  4:3,
                  5:4,
                  6:6,
                  7:9,
                  8:25,
                  9:50,
                  10:800}

def get_outcomes():
    outcomes = []
    for i in xrange(11):
        outcomes.append([_RESULTS_TABLE[i], str(_COMBO_PAYOFFS[i]) + "x"])
    return outcomes

class Level2Page(BaseRequestHandler):
    
    def get(self):
        if (users.is_current_user_admin()):
            self.redirect('/admin')
        else:
            information = "This is a single player, slot-like poker " + \
                    "game. You place a bet and get dealt a poker hand " + \
                    "(5 cards). If the hand contains a poker combination " + \
                    " greater than or equal to a pair of Jacks, you win " + \
                    "some money. The better the poker combination, the " + \
                    "more money you win! Good luck!";
            self.display(information=information)
            
    def post(self):
        
        # Look up profiler info and read the form values
        profilers_query = Profiler.all().filter("user =",
                users.get_current_user()).order('-modified')
        profiler = profilers_query.get()
        
        bet = int(self.request.get('bet'))
        
        # If somehow the bet was bigger than the money, go home
        if profiler.money < self.LEVEL2_CUTOFF or bet > profiler.money:
            self.redirect('/')
        else:
            # Deal the cards and see the results
            deck = CardDeck()
            player = Player()
            for i in xrange(5):
                deck.deal_card(player)
            # Clearing out the previous info
            cards = []
            cards = player.get_cards()
            combo = get_top_combo(cards)
            result_message = _RESULT_MESSAGES.get(combo)
                        
            # Calculate the payoff
            payoff = bet * _COMBO_PAYOFFS.get(combo, 0)
            casino_query = Profiler.all().filter("user =",
                    User("Casino")).order('-modified')
            casino = casino_query.get()
            if casino is None:
                casino = Profiler(user = User("Casino"),
                        nickname = "Robert De Niro", money = 0)
            # Store the result
            profiler.money += payoff
            casino.money -= payoff
            profiler.modified = datetime.now()
            profiler.hands_per_level[1] += 1
            casino.put()
            profiler.put()
            
            if profiler.money < 1:
                self.redirect('/')
            else:
                # Load the images
                images = []
                for i in xrange(5):
                    images.append("/images/card_" + str(cards[i]) + ".png")
                new_bet = bet
                # Did you win?
                if payoff > 0:
                    won = "won"
                    delta = payoff
                else:
                    won = "lost"
                    delta = payoff * -1
                    if profiler.money < bet:
                        new_bet = profiler.money
                # Tell what the winnings are
                outcomes = get_outcomes()
                # Put everything we want to put into template_values
                template_values = {'outcomes': outcomes,
                                   'new_bet': new_bet,
                                   'result_message':result_message,
                                   'bet': bet,
                                   'delta': delta,
                                   'won': won,
                                   'images': images}
                self.display(template_values)
    
    def display(self, passed_template_values=[], information=None):
        # Get the guest object for the current user
        profilers_query = Profiler.all().filter("user =",
                users.get_current_user()).order('-modified')
        profiler = profilers_query.get()
        template_values = {'level_name': self.LEVEL2_NAME,
                           'profiler': profiler}
        if information is not None and profiler.hands_per_level[1] < 10:
            template_values['information'] = information
        template_values.update(passed_template_values)
        self.generate('level2.html', template_values)